# Copyright (c) 2005 Jurgen Scheible
# script that connects to the serial port of the PC
# and lets you send characters to the PC

import appuifw
import socket
import e32
import axyz
import graphics
from key_codes import *

sock = None
acc_sensor = None
script_lock = None
keyboard = None
ignore_max = 3
ignore_data = 0
sending = 1

class Keyboard(object):
    def __init__(self,onevent=lambda:None):
        self._keyboard_state={}
        self._downs={}
        self._onevent=onevent
    def handle_event(self,event):
        if event['type'] == appuifw.EEventKeyDown:
            code=event['scancode']
            if not self.is_down(code):
                self._downs[code]=self._downs.get(code,0)+1
            self._keyboard_state[code]=1
        elif event['type'] == appuifw.EEventKeyUp:
            self._keyboard_state[event['scancode']]=0
        self._onevent()
    def is_down(self,scancode):
        return self._keyboard_state.get(scancode,0)
    def pressed(self,scancode):
        if self._downs.get(scancode,0):
            self._downs[scancode]-=1
            return True
        return False



####################################################
#
#			BLUETOOTH
#
####################################################
def bt_connect():
    global sock
    # create a bluetooth socket
    sock = socket.socket(socket.AF_BT,socket.SOCK_STREAM)
    target=''# here you can give the bt address of the other mobile if you know it
    if not target:
        # scan for bluetooth devices
        address,services=socket.bt_discover()
        print "Discovered: %s, %s"%(address,services)
        if len(services)>1:
            choices=services.keys()
            choices.sort()
            # bring up a popup menu and show the available bt devices for selection
            choice=appuifw.popup_menu([unicode(services[x])+": "+x
                                        for x in choices],u'Choose port:')
            target=(address,services[choices[choice]])
        else:
            target=(address,services.values()[0])
    print "Connected to "+str(target)
    # connect to the serial port of the PC
    sock.connect(target)
    print "OK."
        
# define the textinput function
def send_coord(x,y,z):
    global sock, keyboard, ignore_max, ignore_data, sending
    ignore_data += 1
    if ignore_data < ignore_max:
        return
    ignore_data = 0

    if sock:
        if keyboard.is_down(EScancodeRightSoftkey):
            quit()
        elif keyboard.is_down(EScancodeSelect):
            sock.sendall(u'Enter')
            return
        elif keyboard.is_down(EScancode1):
            sock.sendall(u'Key1')
            return
        elif keyboard.is_down(EScancode2):
            sock.sendall(u'Key2')
            return
        elif keyboard.is_down(EScancode3):
            sock.sendall(u'Key3')
            return
        elif keyboard.is_down(EScancode4):
            sock.sendall(u'Key4')
            return
        elif keyboard.is_down(EScancode5):
            sock.sendall(u'Key5')
            return
        elif keyboard.is_down(EScancode6):
            sock.sendall(u'Key6')
            return
        elif keyboard.is_down(EScancode7):
            sock.sendall(u'Key7')
            return
        elif keyboard.is_down(EScancode8):
            sock.sendall(u'Key8')
            return
        elif keyboard.is_down(EScancode9):
            sock.sendall(u'Key9')
            return
        elif keyboard.is_down(EScancode0):
            sock.sendall(u'Key0')
            return
        elif keyboard.is_down(EScancodeStar):
            sock.sendall(u'Star')
            return
        elif keyboard.is_down(EScancodeHash):
            sock.sendall(u'Hash')
            return
        elif keyboard.is_down(EScancodeUpArrow):
            sock.sendall(u'Up')
            return
        elif keyboard.is_down(EScancodeDownArrow):
            sock.sendall(u'Down')
            return
        elif keyboard.is_down(EScancodeLeftArrow):
            sock.sendall(u'Left')
            return
        elif keyboard.is_down(EScancodeRightArrow):
            sock.sendall(u'Right')
            return
        elif keyboard.is_down(EScancodeBackspace):
            sock.sendall(u'Backspace')
            return
        elif keyboard.is_down(EScancodeEdit):
            sock.sendall(u'Edit')
            return
        elif keyboard.pressed(EScancodeLeftSoftkey):
            sending *= -1
        if e32.inactivity() > 4.0:
            e32.reset_inactivity()
        if sending == 1:
            sock.sendall( "%i,%i,%i"%(x,y,z) )
    else:
        quit()


def quit():
    global sock, acc_sensor, script_lock
    axyz.disconnect()
    if sock:
        sock.send(u'end')
        sock.close()
    script_lock.signal()
    appuifw.app.set_exit()


keyboard = Keyboard()
canvas=appuifw.Canvas(event_callback=keyboard.handle_event, redraw_callback=None)
appuifw.app.body=canvas
appuifw.app.title = u'NokChuk'
appuifw.app.exit_key_handler = quit
appuifw.app.screen='large'
background = graphics.Image.open('E:\\Python\\n95.png')
bt_connect()
canvas.blit(background)
axyz.connect(send_coord)

script_lock = e32.Ao_lock()
script_lock.wait()
